package wml.switcher.tranceiver;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.LinkedBlockingQueue;

import wml.switcher.command.Command;
import wml.switcher.command.MarkCommand;

public class CommandSender implements Runnable {

	private LinkedBlockingQueue<Command> commands = new LinkedBlockingQueue<Command>();
	private Socket socket;
	private DataOutputStream dos;

	public CommandSender(String ip, int port) {
		try {
			this.socket = new Socket(ip, port);
			this.dos = new DataOutputStream(socket.getOutputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (true) {
				Command command = this.commands.take();
				this.send(command);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void send(Command command) throws IOException {
		this.dos.writeInt(command.getType());
		if (command instanceof MarkCommand) {
			MarkCommand mc = (MarkCommand) command;
			this.dos.writeInt(mc.getX());
			this.dos.writeInt(mc.getY());
		}
		this.dos.writeInt(command.getPosition());
		this.dos.flush();
	}

	public void sendCommand(Command command) {
		this.commands.offer(command);
	}
}
